<?php
require_once("include/bittorrent.php");
dbconn();
require_once(get_langfile_path());
require "memcache.php";
if (isset($_GET['checknew'])) {
	echo file_get_contents("shoutbox_new.html");
	die;
}
if (isset($_GET['del'])) {
	if (is_valid_id($_GET['del'])) {
		if ((get_user_class() >= $sbmanage_class || $CURUSER['id'] == $_GET['userid'])) {
			sql_query("DELETE FROM shoutbox WHERE id = " . mysql_real_escape_string($_GET['del']));
			write_log($CURUSER['username'] . "删掉了一条群聊发言", 'normal');
		}
	}
}
$where = $_GET["type"];
?>
<html>
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
		<link rel="stylesheet" href="<?php echo get_font_css_uri() ?>" type="text/css">
		<link rel="stylesheet" href="<?php echo get_css_uri() . "theme.css" ?>" type="text/css">
		<link rel="stylesheet" href="styles/curtain_imageresizer.css" type="text/css">
		<script src="curtain_imageresizer.js" type="text/javascript"></script><style type="text/css">body {overflow-y:scroll; overflow-x: hidden}</style>
		<?php
		print(get_style_addicode());
		?>
		<script type="text/javascript">
			//<![CDATA[
			var t;
			function countdown(time)
			{
				if (time <= 0) {
					parent.document.getElementById("hbtext").disabled = false;
					parent.document.getElementById("hbsubmit").disabled = false;
					parent.document.getElementById("hbsubmit").value = parent.document.getElementById("sbword").innerHTML;
				} else {
					parent.document.getElementById("hbsubmit").value = time;
					time = time - 1;
					setTimeout("countdown(" + time + ")", 1000);
				}
			}
			function hbquota() {
				parent.document.getElementById("hbtext").disabled = true;
				parent.document.getElementById("hbsubmit").disabled = true;
				var time = 10;
				countdown(time);
				//]]>
			}

		</script>
		<style>
			/*Shutbox Section*/
			.shoutrow{min-height:42px;border-top:1px solid #aaa;border-bottom:1px solid #aaa;padding:5px;margin:-1px 10px;font-size:14px;}
			.shoutbox_avatar{height:40px;width:40px;margin-right:5px;position:relative;float:left;}
			.shoutbox_main{vertical-align:top;position:relative;margin:0 0 0 48px;font-size:14px;font-weight:normal;}
			.shoutbox_main span,.shoutbox_main span a,.shoutbox_main span a b,.shoutbox_main b{vertical-align:top;}
			.shoutbox_content{word-wrap:break-word;word-break: break-all;}
			.shoutrow .date{position:relative;font-size:12px;color:#aaa;}
			.shoutbox_reply, .shoutbox_del,.shoutbox_user{font-size:12px;}
			.shoutbox_reply a,.shoutbox_del a{color:#aaa;}
			h1{margin-left:10px;}
			/*End Shutbox*/
		</style>
	</head>
	<body class='inframe' <?php if ($_GET["type"] != "helpbox") { ?> onload="<?php echo $startcountdown ?>" <?php } else { ?> onload="hbquota()" <?php } ?>>
		<?php
		if ($_GET["sent"] == "yes") {
			//PHP内再次判断发言间隔
			$date = date("H:i:s");
			$limittime = 5;
			if ($memcache->get('app_shoutbox_' . $CURUSER['id']) != '') {
				$lasttime = $memcache->get('app_shoutbox_' . $CURUSER['id']);
				echo("<script type=\"text/javascript\"> alert(\"你在 $limittime 秒内( $lasttime )刚发过言，休息一会吧。此提示框会出现到时间到了为止，然后大概会把你刚才的发言发出去，抱歉╮(╯▽╰)╭\");location.reload(); </script>");
				die;
			}
			$memcache->set('app_shoutbox_' . $CURUSER['id'], $date, false, $limittime) or die("请向管理员报告此错误");

			if (!$_GET["shbox_text"]) {
				$userid = 0 + $CURUSER["id"];
			} else {
				$text = trim($_GET["shbox_text"]);
				if ($_GET["type"] == "helpbox") {
					if ($showhelpbox_main != 'yes') {
						write_log("Someone is hacking shoutbox. - IP : " . getip(), 'mod');
						die($lang_shoutbox['text_helpbox_disabled']);
					}
					$userid = 0;
					$type = 'hb';
				} elseif ($_GET["type"] == 'shoutbox') {
					$userid = 0 + $CURUSER["id"];
					if (!$userid) {
						write_log("Someone is hacking shoutbox. - IP : " . getip(), 'mod');
						die($lang_shoutbox['text_no_permission_to_shoutbox']);
					}
					if ($_GET["toguest"]) {
						$type = 'hb';
					} else {
						if (strpos($text, "@游客") > 0)
							$type = 'hb';
						else
							$type = 'sb';
					}
				}
				$date = sqlesc(time());

				sql_query("INSERT INTO shoutbox (userid, date, text, type, ip) VALUES (" . sqlesc($userid) . ", $date, " . sqlesc(RemoveXSS(trim($text))) . ", " . sqlesc($type) . ", " . sqlesc(getip()) . ")") or sqlerr(__FILE__, __LINE__);

				file_put_contents("shoutbox_new.html", mysql_insert_id());
				if ($memcache->get('robotname') == '') {
					$robotname = mysql_fetch_array(sql_query("SELECT username FROM users WHERE id = $robotusers")) or sqlerr(__FILE__, __LINE__);
					$memcache->set('robotname', $robotname[0], false, 3600 * 24 * 7);
				} else {
					$robot = $memcache->get('robotname');
				}
				if (preg_match("/\[\@$robot\]/i", $text) == 1) {
					//智能聊天机器人--开始
					$reqInfo = str_replace("[@$robot] ", "", $text); //只保留输入的部分
					//小逗比智能聊天机器人--开始
					//$apikey = "CCF9F705-97F0-A442-95B3-5D1808617C30";
					//$url = "http://api.xiaodoubi.com/api.php?key=$apikey&chat=$reqInfo";
					//小逗比智能聊天机器人--结束
					//图灵智能聊天机器人--开始
					$apikey = "1e89b891798aa7d5990ab82961034382";
					$url = "http://www.tuling123.com/openapi/api?key=$apikey&info=$reqInfo";
					//图灵智能聊天机器人--结束
					$ch = curl_init();
					$timeout = 5;
					curl_setopt($ch, CURLOPT_URL, $url);
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
					curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
					$file_contents = curl_exec($ch);
					curl_close($ch);
					//$answer = str_replace(array("\\r\\n", "[小逗比"), array("[br]", "["), $file_contents); //小逗比过滤
					//sendshoutbox("[@$CURUSER[username]]：$answer", "", "", $date + 5); //小逗比输出
					$answer = json_decode($file_contents, true); //图灵
					$tulingtext = $answer['text']; //文本
					$tulingurl = $answer['url']; //连接
					$tulinglist = $answer['list'][0]['detailurl']; //详情链接
					sendshoutbox("[@$CURUSER[username]]：$tulingtext" . " $tulingurl" . " $tulinglist", "", "", $date + 5); //图灵输出
					//智能聊天机器人--结束
				} else {
					at_user_message($text, '', 'shoutbox'); //@用户时，对该用户发送PM
				}
				print "<script type=\"text/javascript\">parent.document.forms['shbox'].shbox_text.value='';</script>";
			}
		}

		$limit = ($CURUSER['sbnum'] ? $CURUSER['sbnum'] : 50);
		if ($where == "helpbox") {
			$sql = "SELECT * FROM shoutbox WHERE type='hb' ORDER BY date DESC LIMIT " . $limit;
		} elseif ($CURUSER['hidehb'] == 'yes' || $showhelpbox_main != 'yes') {
			$sql = "SELECT * FROM shoutbox WHERE type='sb' ORDER BY date DESC LIMIT " . $limit;
		} elseif ($CURUSER) {
			$sql = "SELECT * FROM shoutbox ORDER BY date DESC LIMIT " . $limit;
		} else {
			die("<h1>" . $lang_shoutbox['std_access_denied'] . "</h1>" . "<p>" . $lang_shoutbox['std_access_denied_note'] . "</p></body></html>");
		}
		$res = sql_query($sql) or sqlerr(__FILE__, __LINE__);
		if (mysql_num_rows($res) == 0) {
			print("<table border='0' cellspacing='0' cellpadding='2' width='100%' align='left' style='word-break: break-all; word-wrap:break-word;table-layout: fixed;'>");
			if ($groupchat != '') {
				print("<div class=\"shoutrow\"><font style=\"color: red\">{$groupchat}</font></div>");
			}
			print("</table>");
		} else {
			?>
			<script type="text/javascript" src="jquerylib/jquery-1.7.2.min.js"></script>
			<script type="text/javascript">
				function retuser(value) {
					//var c = $("#shbox_text", window.parent.document);
					//c.val(c.val() + "[@" + value + "] ");
					//c.focus();
					//c = $("#hbtext", window.parent.document);
					//c.val(c.val() + "[@" + value + "] ");
					//c.focus();
					var shbox_text = parent.document.getElementById('shbox_text');
					shbox_text.focus();
					shbox_text.value = '[@' + value + '] ';
				}
			</script>
			<?php
			print("<table border='0' cellspacing='0' cellpadding='2' width='100%' align='left' style='word-break: break-all; word-wrap:break-word;table-layout: fixed;'>");
			if ($groupchat != '') {
				print("<div class=\"shoutrow\"><font style=\"color: red\">{$groupchat}</font></div>");
			}
			$i = 1;
			while ($arr = mysql_fetch_assoc($res)) {
				if (get_user_class() >= $sbmanage_class || $CURUSER['id'] == $arr['userid']) {
					$del = "[<a onclick=\"if(confirm('确定要删除吗？')){window.location.href='shoutbox.php?del={$arr['id']}&userid={$arr['userid']}';}\" style=\"cursor:pointer\">{$lang_shoutbox['text_del']}</a>]";
				}
				if ($arr["userid"]) {
					$username = get_username($arr["userid"], false, true, true, true, false, false, "", true);
					$arr2 = get_user_row($arr["userid"]);
					if ($_GET["type"] != 'helpbox' && $arr["type"] == 'hb')
						$username .= $lang_shoutbox['text_to_guest'];
				} else {
					$school = strpos($arr["ip"], ':') ? school_ip_location($arr["ip"], false) : '';
					$userip = str_replace(':', '', $arr['ip']);
					$guestid = substr($userip, strlen($userip) - 8);
					$username = "<b title='" . $school . "'>游客" . $guestid . "</b>";
					$arr2["username"] = "游客" . $guestid;
				}
				if ($CURUSER['timetype'] != 'timealive')
					$time = strftime("%m.%d %H:%M", $arr["date"]);
				else
					$time = get_elapsed_time($arr["date"]) . $lang_shoutbox['text_ago'];
				$messtext = str_replace("[@" . $CURUSER['username'] . "]", "[color=Red][b]@" . $CURUSER['username'] . "[/b][/color]", $arr["text"]);  //将回复给自己的名字染红
				print("<div class=\"shoutrow\">" . $username . "：<span class=\"shoutbox_content\">" . format_comment($messtext, true, false, true, true, 600, true, false) . "</span><br /><span class='date'>[" . $time . "]</span>" . ((get_user_class() >= $sbmanage_class || $CURUSER['id'] == $arr['userid']) ? " <span class=\"shoutbox_del\">{$del}</span>" : "") . "<span class=\"shoutbox_reply\"><a onclick=\"retuser('" . $arr2["username"] . "');\" style=\"cursor:pointer\"> | [@]</a></span></div>\n");
				$i++;
			}
			print("</table>");
		}
		?>
	</body>
</html>
